//添加时间戳
var timestamp = new Date().getTime();

//get方法
function get_Data(url, data, success, error) {
    var token = getToken() || '';
    if (token == '') {
        logout();
        return;
    }
    if (url == '' || url == undefined) {
        return;
    }
    var paramData = '';
    if (data) {
        var params = [];
        for (var key in data) {
            params.push(key + '=' + data[key]);
        }
        paramData = params.join('&');
    }
    $.ajax({
        type: 'GET',
        url: url,
        data: paramData,
        timeout: 2000,
        beforeSend: function (request) {
            request.setRequestHeader("Authorization", getToken());
        },
        success: function (res, status, xhr) {
            var token = xhr.getResponseHeader("Authorization") || '';
            setToken(token);
            var ajaxres = res;
            if (typeof (res) != 'object') {
                ajaxres = JSON.parse(res);
            }
            if (ajaxres.code != 0) {
                if (ajaxres.code == 10001) {
                    layer.alert(ajaxres.message, function () {
                        logout();
                        return;
                    });
                }
                var msg = ajaxres.message + '，错误码：' + ajaxres.code;
                layer.alert(msg);
            }
            if (ajaxres.code == 0) {
                if (success && typeof (success) == 'function') {
                    success(ajaxres);
                }
            } else {
                if (error && typeof (error) == 'function') {
                    error(ajaxres);
                }
            }
        },
        error: function (xhr) {
            if (xhr.status == 404) {
                layer.alert('请求失败404');
            } else if (xhr.status == 500) {
                layer.alert('请求失败500');
            }
        }
    });
}

//post方法
function postData($,url, data, success, error) {
    var token = getToken() || '';
    if (token == '') {
        logout();
        return;
    }
    if (url == '' || url == undefined) {
        return;
    }
    $.ajax({
        type: 'POST',
        url: url,
        data: data,
        beforeSend: function (request) {
            request.setRequestHeader("Authorization", getToken());
        },
        success: function (res, status, xhr) {
            var token = xhr.getResponseHeader("Authorization") || '';
            setToken(token);
            var ajaxres = res;
            if (typeof (res) != 'object') {
                ajaxres = JSON.parse(res);
            }
            if (ajaxres.code != 0) {
                if (ajaxres.code == 10001) {
                    layer.alert(ajaxres.message, function () {
                        // logout();
                        return;
                    });
                }
                var msg = ajaxres.message + '，错误码：' + ajaxres.code;
                layer.alert(msg);
            }
            if (ajaxres.code == 0) {
                if (success && typeof (success) == 'function') {
                    success(ajaxres);
                }
            } else {
                if (error && typeof (error) == 'function') {
                    error(ajaxres);
                }
            }
        },
        error: function (xhr) {
            console.log(xhr)
            if (xhr.status == 404) {
                layer.alert('请求失败404');
            } else if (xhr.status == 500) {
                layer.alert('请求失败500');
            }
        }
    });
}

function getCaptcha(element_id) {
    $.ajax({
        type: 'GET',
        url: captcha,
        success: function (res) {
            if (res.code != 0) {
                if (res.code == 10001) {
                    layer.alert(res.message, function () {
                        // logout();
                        return;
                    });
                }
                var msg = res.message + '，错误码：' + res.code;
                layer.alert(msg);
                return;
            }
            capcha_id = res.data.id;
            setCookie(cookie_captcha_name, capcha_id);
            $('#' + element_id).attr('src', res.data.value);
        },
        error: function (xhr) {
            console.log(xhr)
            if (xhr.status == 404) {
                layer.alert('请求失败404');
            } else if (xhr.status == 500) {
                layer.alert('请求失败500');
            }
        }
    });

}

/**
 *获取id
 */
function guid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

function url(filePath) {
    return filePath + '.html' + '?_=' + timestamp;
}

//页面跳转
function redirect(url) {
    var flag = url.indexOf('?');
    if (flag > 0) {
        window.location.href = url + '&_=' + timestamp;
        return;
    }
    window.location.href = url + '?_=' + timestamp;
    return;
}

function locationReplace(url) {
    var flag = url.indexOf('?');
    if (flag > 0) {
        url += '&_=' + timestamp;
    } else {
        url += '?_=' + timestamp;
    }
    location.replace(url);
}


function setCache(key, loca_data) {
    if (!window.localStorage) {
        layer.alert('浏览器不支持localstorage');
    } else {
        var storage = window.localStorage;
        if (key == token_key) {
            storage.setItem(key, loca_data);
            return;
        }
        storage.setItem(key, JSON.stringify(loca_data));
    }
}

//获取缓存
function getCache(key) {
    if (!window.localStorage) {
        layer.alert('浏览器不支持localstorage');
    } else {
        var storage = window.localStorage;
        if (key == token_key) {
            return storage.getItem(key)
        }
        return JSON.parse(storage.getItem(key));
    }
}

//删除缓存
function deleteCache(key) {
    if (!window.localStorage) {
        layer.alert('浏览器不支持localstorage');
    } else {
        var storage = window.localStorage;
        storage.removeItem(key);
    }
}

//封装过期控制代码
function setCache_outTime(key, value) {
    if (!window.localStorage) {
        layer.alert('浏览器不支持localstorage');
    } else {
        var curTime = new Date().getTime();
        localStorage.setItem(key, JSON.stringify({data: value, time: curTime}));
    }

}

function getCache_outTime(key, exp) {
    var data = localStorage.getItem(key);
    var dataObj = JSON.parse(data);
    var now_time = new Date().getTime();
    if (now_time / 1000 - dataObj.time / 1000 > exp) {
        console.log('信息已过期');
        return false;
    } else {
        var dataObjDatatoJson = dataObj.data;
        return dataObjDatatoJson;
    }
}

//检查登录状态，未登录跳转到登录页
function checkLogin() {
    var token = getToken();
    if (token == '' || token == undefined) {
        if (is_local) {
            locationReplace('page/login.html');
        } else {
            window.opener = null;
            window.open('', '_self');
            window.close();
            return;
        }
    }
}

function setToken(token) {
    setCache(token_key, token)
}

function getToken() {
    return getCache(token_key) || '';
}

function logout() {
    clearToken(token_key);
    window.location.href = '/login';
}

function clearToken() {
    if (!window.localStorage) {
        layer.alert('浏览器不支持localstorage');
    } else {
        var storage = window.localStorage;
        storage.removeItem(token_key);
    }
    storage.removeItem('user');
}

//从地址里面拿参数
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

//获取地址栏参数//可以是中文参数
function getUrlParam(key) {
    // 获取参数
    var url = window.location.search;
    // 正则筛选地址栏
    var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
    // 匹配目标参数
    var result = url.substr(1).match(reg);
    //返回参数值
    return result ? decodeURIComponent(result[2]) : null;
}

function GetUrlString(url, name) {
    console.log(url)
    if (url.indexOf('?') != -1) {
        url = url.split('?')[1];
        console.log(url)
    }
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = url.match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

function getScreen(maxW, maxH) {
    var arr = [
        document.documentElement.clientWidth || document.body.clientWidth,
        document.documentElement.clientHeight || document.body.clientHeigth
    ];
    maxW && (function () {
        if (arr[0] > maxW) {
            arr[0] = maxW;
        }
    }());
    maxH && (function () {
        if (arr[1] > maxH) {
            arr[1] = maxH;
        }
    }());
    return arr;
}


function tolog(data) {
    getData(siteUrl + 'server/tolog', {data: data});
}

//获取用户登录信息
function login() {
    var params = GetQueryString('params');
    if (params) {
        var member_info = JSON.parse(unescape(params));
        setCache(login_key, member_info);
    }
}

//非空判断
function isEmpty(data) {
    if (data == undefined || data == null || data == '') {
        return true;
    } else {
        return false;
    }
}

//获取当前时间
function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
        + " " + date.getHours() + seperator2 + date.getMinutes()
        + seperator2 + date.getSeconds();
    return currentdate;
}

//写cookies

function setCookie(name, value) {
    var Days = 30;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}

//读取cookies
function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");

    if (arr = document.cookie.match(reg))

        return unescape(arr[2]);
    else
        return null;
}

//删除cookies
function delCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null)
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}

//验证域名
function check_domain(newName) {
    var regEn = /[`!@#$%^&*()_+<>?:"{},\/;'[\]]/im,
        regCn = /[·！#￥（——）：；“”‘、，|《。》？、【】[\]]/im;
    if (regEn.test(newName) || regCn.test(newName)) {
        layer.alert('域名错误，请重新输入');
        return false;
    }
}

//ip地址转int
function ipToint(ip) {
    if (!ip || ip.length == 0) {
        return;
    }
    var ip = ip.split(".");
    ip = Number(ip[0]) * 256 * 256 * 256 + Number(ip[1]) * 256 * 256 + Number(ip[2]) * 256 + Number(ip[3]);
    ip = ip >>> 0;
    return ip;
}

//ip地址验证
function isValidIP(ip) {
    var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
    return reg.test(ip);
}

// 最简单数组去重法
/*
* 新建一新数组，遍历传入数组，值不在新数组就push进该新数组中
* IE8以下不支持数组的indexOf方法
* */
function uniq(array) {
    var temp = []; //一个新的临时数组
    for (var i = 0; i < array.length; i++) {
        if (temp.indexOf(array[i]) == -1) {
            temp.push(array[i]);
        }
    }
    return temp;
}


function setTable(table_obj, elem_id, url, table_cols, table_options) {
    var myoptions = table_options || {};
    return table_obj.render({
        elem: '#' + elem_id,
        url: url,
        headers: {'Authorization': 'Bearer ' + getToken()},
        method: myoptions.method || 'GET',
        parseData: function (res) { //res 即为原始返回的数据
            if (res.data == undefined) {
                res.data = {};
            }
            if (res.data.total_page == undefined) {
                res.data.total_page = 0;
                res.data.data = {};
            }
            return {
                "code": res.code, //解析接口状态
                "msg": res.message, //解析提示文本
                "count": res.data.total_page, //解析数据长度
                "data": res.data.data//解析数据列表
            };
        },
        cellMinWidth: myoptions.cellMinWidth || 95,
        page: myoptions.page || true,
        height: myoptions.height || "full-125",
        limits: myoptions.limits || [1, 5, 10, 15, 20, 25],
        limit: myoptions.limit || 20,
        id: "adminListTable",
        cols: table_cols
    });
}

function dateFormat(fmt, timestamp) {
    let ret;
    var date = new Date(timestamp);
    const opt = {
        "Y+": date.getFullYear().toString(),        // 年
        "m+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "M+": date.getMinutes().toString(),         // 分
        "S+": date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        }
        ;
    }
    ;
    return fmt;
}

function pageRefresh($,element) {
    var href = location.hash.replace(/^#\//, '');
    var container = '.layuimini-content-page';
    $(container).html('');
    $.ajax({
        url: href,
        type: 'get',
        dataType: 'html',
        success: function (data) {
            $(container).html(data);
            element.init();
        },
        error: function (xhr, textstatus, thrown) {
            return layer.msg('Status:' + xhr.status + '，' + xhr.statusText + '，请稍后再试！');
        }
    });
}

function tableReload(table,targetId) {
    table.reload(targetId,{})
}

